using System;
using System.Data;
using System.Web;
using NHibernate;
using NHibernate.Context;
using StructureMap;

namespace ContactCenter.Persistence.NH
{
    public class SessionPerRequestModule : IHttpModule
    {
        private readonly IContainer _container;

        public SessionPerRequestModule(IContainer container)
        {
            _container = container;
        }

        public void Init(HttpApplication context)
        {
            context.BeginRequest += ContextBeginRequest;
            context.EndRequest += ContextEndRequest;
        }

        void ContextEndRequest(object sender, EventArgs e)
        {
            var sessionFactory = _container.GetInstance<ISessionFactory>();

            using (var session = CurrentSessionContext.Unbind(sessionFactory))
            {
                if (!session.IsOpen) return;
                
                if (HttpContext.Current.Error != null)
                {
                    session.Transaction.Rollback();
                }
                else
                {
                    session.Transaction.Commit();
                }
                    
                session.Close();
            }
        }

        void ContextBeginRequest(object sender, EventArgs e)
        {
            var sessionFactory = _container.GetInstance<ISessionFactory>();

            var session = sessionFactory.OpenSession();

            session.BeginTransaction(IsolationLevel.ReadCommitted);

            CurrentSessionContext.Bind(session);
        }

        public void Dispose()
        {
        }
    }
}